package com.cskaoyan.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.BaseBusinessException;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    private StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {

        //扣减库存

        /**
         * 扣减库存
         */
        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        List<CartProductDto> dtoList = createOrderContext.getCartProductDtoList();
        List<Long> buyProductIds = createOrderContext.getBuyProductIds();

        if (CollectionUtils.isEmpty(buyProductIds)) {
            buyProductIds = dtoList.stream().map(u -> u.getProductId()).collect(Collectors.toList());

        }
        //根据大小排序(排不排无所谓)
        buyProductIds.sort(Long::compareTo);
        //开始扣减库存


        //查出库存后锁定库存
        List<Stock> stocksList = stockMapper.findStocksForUpdate(buyProductIds);

        if (CollectionUtils.isEmpty(stocksList)) {
            throw new BizException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(),"库存未初始化");
        }
        if (stocksList.size() != buyProductIds.size()) {
            throw new BizException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(),"部分商品未初始化");
        }


        //扣减库存

        for (CartProductDto cartProductDto : dtoList) {
            @NotNull @Min(0) Long productId = cartProductDto.getProductId();
            Long productNum = cartProductDto.getProductNum();

            //productNum不能超出限购数量 此处需要判断
            // if (productNum > cartProductDto.getLimitNum()) {
            //     throw new BizException("商品购买数量超出购买限制!");
            // }
            for (Stock stock : stocksList) {
                if (stock.getItemId().compareTo(productId) == 0 && productNum.intValue() > stock.getRestrictCount().intValue()){
                    throw new BizException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(),"商品购买数量超出购买限制!");
                }
                if ((stock.getItemId().intValue() == productId.intValue()) && (stock.getStockCount().intValue() < productNum.intValue())){
                    throw new BizException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(),"库存不足！");
                }else if (stock.getItemId().intValue() == productId.intValue() && stock.getStockCount().intValue() == 0){
                    throw new BizException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(),"库存为0");
                }
            }


            Stock stock = new Stock();
            stock.setItemId(productId);
            stock.setLockCount(productNum.intValue());
            stock.setStockCount(-productNum);
            stockMapper.updateStock(stock);
        }
        return true;
    }
}